//
//  RootViewController.m
//  GXWN
//
//  Created by iMacOne on 15/11/5.
//  Copyright © 2015年 UNOHACHA. All rights reserved.
//

#import "RootViewController.h"
#import "Size.h"
#import "ToolUtil.h"
#import "ImageUtil.h"
#import "WebUtil.h"
@interface RootViewController (){
    NSTimer *promptTimer;

}

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }

//    [ToolUtil createLine:margin_64 superView:self.view lift:0 width:WindowWidth hight:0.5 color:[UIColor cyanColor]];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)jump:(NSString*)fromText to:(RootViewController*)toVC 
{
    if (toVC == nil) {
        NSLog(@"kaka");
    }
    toVC.fromControl = self;
    CATransition * transition = [CATransition animation];//自定义动画
    transition.duration = 0.3;//动画时间
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];// 动画时间控制
    transition.delegate = self;// 是否代理
    transition.type = kCATransitionPush;// 动画类型
    transition.subtype = kCATransitionFromRight;
    [self.navigationController pushViewController:toVC animated:NO];
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
}
- (void)doBack:(UIButton*)btnBack 
{
    CATransition *transition = [CATransition animation];// 自定义动画
    transition.duration = 0.3;// 动画时间
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];// 动画时间控制
    transition.delegate = self;// 是否代理
    transition.type = kCATransitionPush;// 动画类型
    transition.subtype = kCATransitionFromLeft;
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    self.tabBarController.tabBar.hidden = NO;

}
- (void)prompt:(NSString*)msg{
    [self.view endEditing:YES];
    if (nil != promptTimer) {
        [promptTimer invalidate];
        promptTimer = nil;
    }
    UILabel *label = (UILabel*) [self.view viewWithTag:300];
    msg = ([ToolUtil isBlank:msg] ? @"" : msg);
    if (nil == label) {
        label = [[UILabel alloc] init];
        [self.view addSubview:label];
        label.backgroundColor = [UIColor blackColor];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = FONT(14);
        label.alpha = 0.6;
        [label.layer setCornerRadius:margin_3];
        [label.layer setMasksToBounds:YES];
        label.tag = 300;
        label.numberOfLines = 0;
    }
    CGSize size = [msg sizeWithFont:label.font constrainedToSize:CGSizeMake(WindowWidth - title_height, MAXFLOAT)];
//     CGSize size = [ToolUtil autoWidth1:msg width:WindowWidth - title_height height:MAXFLOAT num:14];
    int width = size.width + title_height / 2, height = size.height + title_height / 4;
    width = (width < title_height * 2 ? title_height * 2 : width);
    int x = (WindowWidth - width) / 2, y = WindowHeight - height - bottom_height - margin_5;
    CGRect tempFrame = label.frame;
    tempFrame = CGRectMake(x, y, width, height);
    label.frame = tempFrame;
    label.text = msg;
    label.hidden = NO;
    promptTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(clearPromptTimer) userInfo:nil repeats:NO];
    
}
- (void)clearPromptTimer {
    UILabel *label = (UILabel*) [self.view viewWithTag:300];
    label.hidden = YES;
    [promptTimer invalidate];
    promptTimer = nil;
}
- (int)createTitle:(NSString*)title midTitle:(NSString *)midTitle
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, taskbar_height, WindowWidth, title_height)];
    titleView.alpha = 1;
    titleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titleView];
    
    CGSize size = [title sizeWithAttributes:@{NSFontAttributeName : FONT(15)}];
    
    int img_h = title_height * 0.47, img_w = img_h * 0.6, lbl_w = size.width, lbl_h = size.height;
    UIImageView *imgBack = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back"]];
    imgBack.frame = CGRectMake(6, (title_height - img_h) / 2, img_w, img_h);
    
    UIImageView * setImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"setting-icon-3@2x"]];
    setImageView.frame = CGRectMake(- 7, (title_height - img_h) / 2, img_h, img_h);
    
    int lbl_x = CGRectGetMaxX(imgBack.frame) + 2, lbl_y = (title_height - lbl_h) / 2;
    
    UILabel *lblBack = [[UILabel alloc] initWithFrame:CGRectMake(lbl_x, lbl_y, (lbl_w < taskbar_height ? taskbar_height : lbl_w), lbl_h)];
    lblBack.text = title;
    lblBack.font = FONT(14);
    
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, CGRectGetMaxX(lblBack.frame) + 4, title_height)];
    //    [btnBack setBackgroundImage:image_top_def1 forState:UIControlStateHighlighted];
    [btnBack addSubview:imgBack];// 按钮上的图标
    [btnBack addSubview:lblBack];// 按钮上的文字
    [btnBack addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:btnBack];// 后退按钮
    
    
    
    if (title.length == 0) {
        btnBack.hidden = YES;
        btnBack.enabled = NO;
    }
    
    int lblTitle_x = CGRectGetMaxX(btnBack.frame), lblTitle_w = WindowWidth - lblTitle_x * 2;
    self.lblTopTitle = [[UILabel alloc] initWithFrame:CGRectMake(lblTitle_x, 0, lblTitle_w, title_height)];
    [self.lblTopTitle setFont:FONT(17)];
    self.lblTopTitle.textAlignment = NSTextAlignmentCenter;
    self.lblTopTitle.text = midTitle;
    [titleView addSubview:self.lblTopTitle];// 正标题
    
    if ([self.lblTopTitle.text isEqualToString:@"我"]) {
        
        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(WindowWidth - 20, 0, 20, title_height)];
        //    [btnBack setBackgroundImage:image_top_def1 forState:UIControlStateHighlighted];
        [rightButton addSubview:setImageView];// 按钮上的图标
        [rightButton addSubview:lblBack];// 按钮上的文字
        [rightButton addTarget:self action:@selector(doLineButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        rightButton.tag = 300;
        [titleView addSubview:rightButton];
    }else if ([self.lblTopTitle.text isEqualToString:@"详情"]){
        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(WindowWidth - margin_34, 0, margin_34, title_height)];
        //    [btnBack setBackgroundImage:image_top_def1 forState:UIControlStateHighlighted];
//        [rightButton addSubview:setImageView];// 按钮上的图标
//        [rightButton addSubview:lblBack];// 按钮上的文字
        rightButton.titleLabel.font = FONT(14);
        [rightButton setTitle:@"分享" forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(doLineButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        rightButton.tag = 1007;
        [titleView addSubview:rightButton];

    }

    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titleView.frame), WindowWidth, 1)];
    [self.view addSubview:line];
    return CGRectGetMaxY(line.frame);
    
}
- (NSDictionary *)createLineButton:(UIScrollView *)scrollView dataDic:(NSDictionary *)dataDic last_y:(float)last_y
{
    int button_h = title_height + 3, icon_w = button_h * 0.6, margin = 12;
    NSArray * titlesArray = dataDic[@"titles"];//名称
    NSArray * icons = dataDic[@"icons"];//图标(可以是nil)
    NSArray * margins = [dataDic[@"margins"] componentsSeparatedByString:@","];
    
    NSArray *lineTops = [dataDic[@"lineTops"]componentsSeparatedByString:@","];// 是否有上边线
    
    NSArray *bottomShorts = [dataDic[@"bottomShorts"] componentsSeparatedByString:@","];// 下边线是否短一点
    NSArray *values = dataDic[@"values"];// 对应的值(可以为nil)
    NSMutableArray *lblValues = [NSMutableArray array];// 考虑到value需要更新，所以必须返回这个UILabel
    
    
    UIView *line = nil;
    for (int i = 0; i < titlesArray.count; i++) {
        
//        if ([lineTops[i] intValue] == 1) {
//            line = [[UIView alloc] initWithFrame:CGRectMake(0, [margins[i] intValue] + last_y, scrollView.frame.size.width, 0.5)];
//            line.backgroundColor = [UIColor grayColor];
//            [scrollView addSubview:line];
//            last_y = CGRectGetMaxY(line.frame);
//        }
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, last_y, scrollView.frame.size.width, button_h)];
        [button addTarget:self action:@selector(doLineButtonClick:) forControlEvents:UIControlEventTouchUpInside];
////        [button setBackgroundImage:image_top_def1 forState:UIControlStateHighlighted];
        button.backgroundColor = [UIColor whiteColor];
        button.tag = 1000 + i;
        button.titleLabel.text = titlesArray[i];
        [scrollView addSubview:button];
        last_y = CGRectGetMaxY(button.frame);
//
        
//        NSLog(@"%@",icon);
        UIImageView * icon = nil;
        if (nil != icons) {
            icon = [[UIImageView alloc] initWithFrame:CGRectMake(margin,  10, 30, 20)];
//            icon.image = [UIImage imageNamed:@"lunbotu1"];
            icon.backgroundColor = [UIColor blackColor];
//            icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lunbotu1.jpg"]];
//            float icon_h = ((float) icon_w) * (icon.image.size.height / icon.image.size.width);
//            icon.frame = CGRectMake(margin, 70 + (title_height + 3)*i, icon_w, 20);
            [button addSubview:icon];
        }
        
//        CGSize size = [titlesArray[i] sizeWithAttributes:@{NSFontAttributeName : FONT(15)}];
//        int label_x = (nil != icon ? CGRectGetMaxX(icon.frame) : 0) + margin, label_y = (button_h - size.height) / 2;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(icon.frame ) + 10, 10, 80, 30)];
        label.text = titlesArray[i];
        label.font = FONT(15);
        [button addSubview:label];
        int arrow_h = button_h * 0.36, arrow_w = arrow_h * 0.57, arrow_y = (button_h - arrow_h) / 2, arrow_x = scrollView.frame.size.width - arrow_w - margin;
//        if (nil != values) {
//            int value_x = CGRectGetMaxX(label.frame) + margin, value_w = arrow_x - value_x - margin * 2;
//            UILabel *value = [[UILabel alloc] initWithFrame:CGRectMake(value_x, label_y, value_w, size.height)];
//            value.text = values[i];
//            value.font = FONT(15);
//            value.textAlignment = NSTextAlignmentRight;
//            [button addSubview:value];
//            [lblValues addObject:value];
//        }
        UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ico_arrow"]];
        arrow.frame = CGRectMake(arrow_x, arrow_y, arrow_w, arrow_h);
        [button addSubview:arrow];
//
//        float line_x = ([bottomShorts[i] intValue] == 1 ? margin : 0), line_w = scrollView.frame.size.width - line_x;
        
//        line = [[UIView alloc] initWithFrame:CGRectMake(0, 70 + (title_height + 3)*i , WindowWidth, 0.5)];
//        line.backgroundColor = [UIColor grayColor ];
//        [scrollView addSubview:line];
        
//        last_y = CGRectGetMaxY(line.frame);
    }
    for (int i = 0; i < titlesArray.count + 1; i++) {
        line = [[UIView alloc] initWithFrame:CGRectMake(0, 70 + (title_height + 3)*i , WindowWidth, 0.5)];
        line.backgroundColor = [UIColor grayColor ];
        [scrollView addSubview:line];
    }
    
    return @{@"last_y" : [NSNumber numberWithFloat:last_y], @"lblValues" : lblValues};
}
- (void)requestTck:(NSString*)_partUrl _param:(NSString*)_param _callback:(ResponseCallback)callback loading_type:(LoadingType)loading_type is_backup:(BOOL)is_backup is_solveFail:(BOOL)is_solveFail _frequency:(int)_frequency
{
    WebUtil * util = [[WebUtil alloc] initWithTck:_partUrl _param:_param _control:self];
    [util requestTck:callback loading_type:loading_type is_backup:is_backup is_solveFail:is_solveFail _frequency:_frequency];
    
}

// 传图上片 {cut:'200',upload:true}
- (void)showUploadImg:(NSString*)param
{
//    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;

    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction * CameraAction = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType1 = UIImagePickerControllerSourceTypeCamera;
        picker.sourceType = sourceType1;
        
        [self presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction * AlbumAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType2 = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.sourceType = sourceType2;
        [self presentViewController:picker animated:YES completion:nil];

    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"h");
        
    }];
    [alertController addAction:CameraAction];
    [alertController addAction:AlbumAction];
    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];
}
//相机相册的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString * type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage * image = info[@"UIImagePickerControllerOriginalImage"];
        [picker dismissViewControllerAnimated:YES completion:nil];
        image = [ImageUtil reduce:image size:CGSizeMake(WindowWidth * 1.5, WindowHeight * 1.5) isAdjust:YES];
        
        BOOL upload = YES;
        if (!upload) {
            NSString * filePath = [ImageUtil saveImageLocal:UIImagePNGRepresentation(image)];
            [self uploadImageAfter:filePath];
            return;
        }
        if ([WebUtil isNet]) {
            [self uploadImageAfter:image];
            
            
            [[[WebUtil alloc] initWithUpload:upload_url _control:self] requestUpload:^(NSMutableDictionary * dic) {
                
                [self uploadImageAfter:@""];
                
            } _data:UIImagePNGRepresentation(image) _fileName:@"temp_image"];
        }
       
        
    }
    
    
}
- (void)uploadImageAfter:(id)object
{
//    NSLog(@"%@",object);

}

#pragma mark 处理扫描结果
- (void)scannerResult:(NSString*)result {
    if ([ToolUtil isBlank:result]) {
        return;
    }
//    if ([ToolUtil isUrl:result]) {
//        [self showBrowser:result isNewWindow:NO];
//        return;
//    }
//    if ([CodeUtil isVcard:result]) {
//        Card *card = [CodeUtil readVcard:result];
//        ScannerCardControl *control = [[ScannerCardControl alloc] init];
//        [self jump:@"" to:control redirect:redirect_type_none keys:@[param_key] values:@[card]];
//        return;
//    }
//    [ToolUtil alert:result];
}

#pragma mark 线性按钮的单击事件
- (void)doLineButtonClick:(UIButton*)btn {
//    NSLog(@"hlhjl");
}
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataArray;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
